package com.qf.commons.sentinel.config;

import com.alibaba.csp.sentinel.cluster.ClusterStateManager;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientAssignConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfig;
import com.alibaba.csp.sentinel.cluster.client.config.ClusterClientConfigManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

/**
 * 集群流控客户端的配置
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Slf4j
public class ClusterFlowClientConfiguration implements CommandLineRunner {

    @Autowired
    private SentinelNacosConfig sentinelNacosConfig;

    @Override
    public void run(String... args) throws Exception {
        log.info("[cluster flow] - 开启集群流控客户端的相关配置.....");
        /**
         * 配置当前模式为客户端
         */
        ClusterStateManager.applyState(ClusterStateManager.CLUSTER_CLIENT);
        //配置服务端地址
        ReadableDataSource<String, ClusterClientAssignConfig> ds =
                new NacosDataSource<>(
                        sentinelNacosConfig.getHost(),
                        sentinelNacosConfig.getGroup(),
                        sentinelNacosConfig.getClusterflowServer(),
                        source -> JSON.parseObject(source,
                                new TypeReference<ClusterClientAssignConfig>() {}));
        ClusterClientConfigManager.registerServerAssignProperty(ds.getProperty());
        //配置客户端相关配置
        ReadableDataSource<String, ClusterClientConfig> ds2 =
                new NacosDataSource<>(
                        sentinelNacosConfig.getHost(),
                        sentinelNacosConfig.getGroup(),
                        sentinelNacosConfig.getClusterflowServer(),
                        source -> JSON.parseObject(source,
                                new TypeReference<ClusterClientConfig>() {}));
        ClusterClientConfigManager.registerClientConfigProperty(ds2.getProperty());
    }
}
